package com.google.project.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.project.client.Service.LoginService;
import com.google.project.server.entity.Users;
import com.google.project.shared.CryptString;
import com.google.project.shared.UsersDTO;

@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {
	
	//check login
	@Override
	public boolean checkLogin() {
		HttpServletRequest request = this.getThreadLocalRequest();
		// dont create a new one -> false
		HttpSession session = request.getSession(false);
		if (session == null || session.getAttribute("UserID") == null)
			return false;
		// session and userid is available, looks like user is logged in.
		return true;
	}
	//check name,pass
	@SuppressWarnings("unchecked")
	@Override
	public String login(String name, String password)
			throws IllegalArgumentException {
		CryptString cryptPass=new CryptString();
		// Escape data from the client to avoid cross-site script
		// vulnerabilities.
		name = escapeHtml(name);
		password =  escapeHtml(password);
		AppMisc.populateDataStoreOnce();
		//check username,pass
		List<UsersDTO> userList = new ArrayList<UsersDTO>();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		//cryptPass.encryptPassword(password)
		String WhereString = "  userName ==  \""+name+"\""+ " && password ==  \""+cryptPass.encryptPassword(password)+"\"";
		Query q= pm.newQuery(Users.class, WhereString);
		try {
			 List<Users> list = (List<Users>)q.execute();
				for (Users user : list) {
					userList.add(user.toDTO());
				}
			 
//			session.setAttribute("userGroup", user.getUserGroup());
		} catch (Exception e) {
			e.getMessage();
		} finally {
			pm.close();
		}
		
		// create session and store userid
		HttpServletRequest request = this.getThreadLocalRequest();
		HttpSession session = request.getSession(true);
		if(userList.size()>0){
			 session.setAttribute("userID",userList.get(0).getUserId());
			 session.setAttribute("userName",userList.get(0).getUserName());
			 session.setAttribute("password",userList.get(0).getPassword());
			 session.setAttribute("fullName",userList.get(0).getFullName());
			 if( userList.get(0).getCurrentProjID()!=null){
				 session.setAttribute("currentProjectID", userList.get(0).getCurrentProjID());
			 }else if(userList.get(0).getCurrentProjID()==null){
				 session.setAttribute("currentProjectID", "");
			 }
			 if(userList.get(0).getUserGroup()!=null){
				 session.setAttribute("userGroup", userList.get(0).getUserGroup());
			 }
			
		}else{
			 session.setAttribute("userID","");
			 session.setAttribute("userName","");
			 session.setAttribute("password","");
			 session.setAttribute("fullName","");
			 session.setAttribute("currentProjectID", "");
			 session.setAttribute("userGroup", -1);
		}
		
		return session.getId();
	
	}
	//logout
	@Override
	public void logout() {
		HttpServletRequest request = this.getThreadLocalRequest();
		// dont create a new one -> false
		HttpSession session = request.getSession(false);
		if (session == null)
			return;
		// do some logout stuff ...
		session.invalidate();
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html
	 *            the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
	//get UserID
	@Override
	public String getUserID() {
		HttpServletRequest request = this.getThreadLocalRequest();
		// dont create a new one -> false
		HttpSession session = request.getSession(false);
		String userID = session.getAttribute("userID").toString();
		return userID;
	}
	//get UserName
	@Override
	public String getUserName() {
		HttpServletRequest request = this.getThreadLocalRequest();
		// dont create a new one -> false
		HttpSession session = request.getSession(false);
		String UserName = session.getAttribute("userName").toString();
		return UserName;
	}
	//get currentProjectID
	@Override
	public String getCurrentProjectID() {
		HttpServletRequest request = this.getThreadLocalRequest();
		// dont create a new one -> false
		HttpSession session = request.getSession(false);
		String currentProjectID = session.getAttribute("currentProjectID").toString();
		return currentProjectID;
	}
	//get currentUserDTO
	@Override
	public UsersDTO getCurrentUserDTO() {
		HttpServletRequest request = this.getThreadLocalRequest();
		// dont create a new one -> false
		HttpSession session = request.getSession(false);
		String userID = session.getAttribute("userID").toString();
		String userName = session.getAttribute("userName").toString();
		String password = session.getAttribute("password").toString();
		String fullName = session.getAttribute("fullName").toString();
		String currentProjectID = session.getAttribute("currentProjectID").toString();
		Long useGroup =Long.parseLong( session.getAttribute("userGroup").toString());
		UsersDTO userDTO=new UsersDTO();
		userDTO.setUserId(userID);
		userDTO.setCurrentProjID(currentProjectID);
		userDTO.setUserName(userName);
		userDTO.setPassword(password);
		userDTO.setFullName(fullName);
		userDTO.setUserGroup(useGroup);
		return userDTO;
	}
}
